package com.coder.rental.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.CarInfo;
import com.coder.rental.service.ICarInfoService;
import com.coder.rental.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 汽车信息 前端控制器
 * </p>
 *
 * @author zhaojj
 * @since 2025-01-10
 */
@RestController
@RequestMapping("/rental/carInfo")
public class CarInfoController {
    @Value("${car.info.maintain-mileage}")
    private Integer maintainMileage;
    @Resource
    private ICarInfoService carInfoService;

    @PostMapping("{start}/{size}")
    public Result search(@PathVariable Integer start,@PathVariable Integer size,@RequestBody CarInfo carInfo){
        Page<CarInfo> page = new Page<>(start,size);
        return Result.success().setData(carInfoService.searchByPage(page,carInfo));
    }
    @PostMapping
    public Result save(@RequestBody CarInfo carInfo){
        // 设置应保次数和实保次数
        int i = carInfo.getMileage() / maintainMileage;
        carInfo.setExpectedNum(i);
        carInfo.setActualNum(i);
        return carInfoService.save(carInfo)? Result.success(): Result.fail();
    }
    @PutMapping
    public Result update(@RequestBody CarInfo carInfo){
        int i = carInfo.getMileage() / maintainMileage;
        carInfo.setExpectedNum(i);
        carInfo.setActualNum(i);
        return carInfoService.updateById(carInfo)?Result.success(): Result.fail();
    }
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids){
        return carInfoService.delete(ids)?Result.success(): Result.fail();
    }

    @PostMapping("exist")
    @Transactional
    public Result exist(@RequestBody CarInfo carInfo){
        System.out.println(carInfo);
        System.out.println(carInfo.getCarNum());
        CarInfo carInfo1 = carInfoService.selectByCarNum(carInfo.getCarNum());
        return ObjectUtil.isNotEmpty(carInfo1)?
                Result.success().setMessage("have"):Result.success().setMessage("no");
    }

    // 查询需要保养的车辆信息
    @GetMapping("toBeMaintain")
    public Result toBeMaintain(){
        return Result.success(carInfoService.toBeMaintain());
    }
}
